package com.chagee.store.operation.server.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.TimeInterval;
import com.alibaba.arms.tracing.Span;
import com.alibaba.arms.tracing.Tracer;
import com.alibaba.fastjson.JSON;
import com.chagee.store.operation.api.enums.PushFinanceStatusEnum;
import com.chagee.store.operation.api.enums.StoreWorkOrderStatusEnum;
import com.chagee.store.operation.common.enums.EmailReceiverTypeEnum;
import com.chagee.store.operation.common.enums.EmailTypeEnum;
import com.chagee.store.operation.server.entity.StoreSettlementDO;
import com.chagee.store.operation.server.entity.WorkOrderDO;
import com.chagee.store.operation.server.event.service.StoreSettlementBaseService;
import com.chagee.store.operation.server.event.service.WorkOrderBaseService;
import com.chagee.store.operation.server.model.bo.ExportOrderEmailBO;
import com.chagee.store.operation.server.service.EmailBizService;
import com.chagee.store.operation.server.utils.DateUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 刷新数据
 * @Author : hk
 * @Date : 2025/1/14
 */

@Component
@Slf4j
@RequiredArgsConstructor
public class RefreshPushFinanceHandler {


	@Resource
	private StoreSettlementBaseService storeSettlementBaseService;

	/**
	 * 处理历史数据刷新待推送状态数据
	 *
	 * @param param
	 * @return
	 */
	@XxlJob("refreshPushFinance")
	public ReturnT<String> refreshPushFinance(String param) {

		Span span = Tracer.builder().getSpan();
		TimeInterval timer = cn.hutool.core.date.DateUtil.timer();
		log.info("处理历史数据刷新待推送状态数据定时任务开始,traceId :{}", span.getTraceId());
		try {

			List<StoreSettlementDO> storeSettlementDOS = storeSettlementBaseService.selectNotPushOrders();

			for (StoreSettlementDO storeSettlementDO : storeSettlementDOS) {
				storeSettlementBaseService.updateSettlement(storeSettlementDO.getSettlementNo(), PushFinanceStatusEnum.NOT_PUSH.getType());
			}
			log.info("处理历史数据刷新待推送状态数据 :{}", JSON.toJSONString(storeSettlementDOS));


		} catch (Exception e) {
			XxlJobLogger.log("处理历史数据刷新待推送状态数据定时任务异常，异常信息:", e);
			log.error("处理历史数据刷新待推送状态数据定时任务异常 => param : {} => 异常信息 :", param, e);
		}

		XxlJobLogger.log("处理历史数据刷新待推送状态数据定时任务结束，共耗时:{},TraceId:{}", timer.intervalRestart(), span.getTraceId());
		return ReturnT.SUCCESS;
	}
}
